//
//  String+substring.swift
//  MobileRTCSwiftSample
//
//  Created by zhangheng on 2019/5/13.
//  Copyright © 2019 Zoom Video Communications, Inc. All rights reserved.
//

import Foundation

// 下标截取任意位置的便捷方法
extension String {
    var lengthcount: Int {
        return self.count
    }
    
    subscript (i: Int) -> String {
        return self[i ..< i + 1]
    }
    
    func substring(fromIndex: Int) -> String {
        return self[min(fromIndex, lengthcount) ..< lengthcount]
    }
    
    @discardableResult
    func substring(toIndex: Int) -> String? {
        return self[0 ..< max(0, toIndex)]
    }
    
    subscript (r: Range<Int>) -> String {
        let range = Range(uncheckedBounds: (lower: max(0, min(lengthcount, r.lowerBound)), upper: min(lengthcount, max(0, r.upperBound))))
        let start = index(startIndex, offsetBy: range.lowerBound)
        let end = index(start, offsetBy: range.upperBound - range.lowerBound)
        return String(self[start ..< end])
    }
    
}
//不包含后几个字符串的方法
extension String {
    func dropLast(_ n: Int = 1) -> String {
        return String(characters.dropLast(n))
    }
    var dropLast: String {
        return dropLast()
    }
}


/// 生成随机字符串
extension String {
    
    /// 生成随机字符串
    ///
    /// - Parameters:
    ///   - count: 生成字符串长度
    ///   - isLetter: false=大小写字母和数字组成，true=大小写字母组成，默认为false
    /// - Returns: String
    static func random(_ count: Int, _ isLetter: Bool = false) -> String {
        
        
        var ch: [CChar] = Array(repeating: 0, count: count)
        for index in 0..<count {
            
            var num = isLetter ? arc4random_uniform(58)+65:arc4random_uniform(75)+48
            if num>57 && num<65 && isLetter==false {
                num = num%57+48
            }else if num>90 && num<97 {
                num = num%90+65
                
            }
            ch[index] = CChar(num)
        }
        
        return String(cString: ch)
    }
    
    /// 生成MD5随机字符串
    ///
    /// - Parameters:
    ///   - count: 生成字符串长度
    ///   - isNumber: false=大小写字母和数字组成，true=只包含，默认为false
    /// - Returns: String
    /*
    static func random_MD5() -> String {
        let randString = arc4random()%1000
        return String(randString).MD5
    }
    */
    
    
    /// 生成随机字符串
    ///
    /// - Parameters:
    ///   - count: 生成字符串长度
    ///   - isNumber: false=大小写字母和数字组成，true=只包含，默认为false
    /// - Returns: String
    static func random_num(_ num:Int,_ isNumber: Bool = false) -> String {
        var string = String()
        var temString  = String()
        for _ in 0..<num {
            
            let number = isNumber ? arc4random()%10:arc4random()%36
            if number<10 {
                let figure = arc4random()%10
                temString = String(format: "%d", figure)
                
            } else {
                let figure = arc4random()%26+97
                let character = CChar(figure)
                temString = String(format: "%c", character)
            }
            string.append(temString)
        }
        //.uppercased() 小写转大写  // .lowercased() 大写转小写
        return string.lowercased()
    }
    
}

extension String {
    func toUppercase() -> String? {
        guard self.isEmpty != true else {
            return nil
        }
        return self.uppercased()
    }
    
    func toLowercase() -> String? {
        guard self.count != 0 else {
            return nil
        }
        return self.lowercased()
    }
    
}


extension String {
    // 获取当前时间转为时间戳
    static func TimeStampNOW() -> String {
        let timer = Int(NSDate().timeIntervalSince1970)
        let timerStr = String(timer)
        return timerStr
    }
    
    // 根据当前时间转为时间戳
    func timeToTimeStamp(time: String) -> Double {
        let dfmatter = DateFormatter()
        dfmatter.dateFormat="yyyy年MM月dd日 HH:mm:ss"
        let last = dfmatter.date(from: time)
        let timeStamp = last?.timeIntervalSince1970
        return timeStamp!
    }
}


extension String {
    func contains(find: String) -> Bool{
        return self.range(of: find) != nil
    }
    func containsIgnoringCase(find: String) -> Bool{
        return self.range(of: find, options: .caseInsensitive) != nil
    }
   
}

extension String {
    //返回第一次出现的指定子字符串在此字符串中的索引
    //（如果backwards参数设置为true，则返回最后出现的位置）
    func positionOf(sub:String, backwards:Bool = false)->Int {
        var pos = -1
        if let range = range(of:sub, options: backwards ? .backwards : .literal ) {
            if !range.isEmpty {
                pos = self.distance(from:startIndex, to:range.lowerBound)
            }
        }
        return pos
    }
  
}
extension String {
    //根据开始位置和长度截取字符串
    func subString(start:Int, length:Int = -1) -> String {
        var len = length
        if len == -1 {
            len = self.count - start
        }
        let st = self.index(startIndex, offsetBy:start)
        let en = self.index(st, offsetBy:len)
        return String(self[st ..< en])
    }
}
